﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.HtmlControls;
using System.Web.UI;
using log4net;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web;

namespace Cn.Edwon.Web.Support {
    public class SupportUtil {
        public static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        public const String OWNER_KEY_DEFAULT = "system";

        public static void DeployBaseURL(Page rPage, HttpRequest rRequest) {
            RegistBaseTag(rPage);
            FixFormAction(rPage,rRequest);
        }
        
        /// <summary>
        /// 为页面统一注册一个base标签，值为网站根目录的url
        /// </summary>
        private static void RegistBaseTag(Page rPage) {
            try {
                HtmlGenericControl _tagBase = new HtmlGenericControl("base");
                _tagBase.Attributes["href"] = ClientHelper.RootUrl;
                rPage.Header.Controls.AddAt(0,_tagBase);
                log.Debug("Register HTML:Base element :" + ClientHelper.RootUrl);
            } catch (Exception ex) {
                log.Error("Register HTML:Base Exception :" + ex.Message);
            }
        }
        /// <summary>
        /// 为页面的From action调整地址，缺省为当前页，因为Base的拼接，需要调整与Base对应。
        /// </summary>
        /// <returns></returns>
        private static void FixFormAction(Page rPage,HttpRequest rRequest) {
            log.Debug("Fix form action");
            try {
                //检查是否存在form节点
                if (rPage.Form == null) {
                    log.Debug("HTML:Form Element not found");
                    return;
                }
                String _action = rPage.Form.Action;

                //检查是否有_action值
                if (String.IsNullOrEmpty(_action)) {
                    log.Debug("Form action is null");
                    rPage.Form.Action = BuildFormAction(rRequest);
                } else {
                    //检查是否为绝对地址
                    log.Debug("Form action :" + _action);
                    if (Regex.IsMatch(_action, "^([a-z]*p:/)?/", RegexOptions.IgnoreCase)) return;

                    String[] _actionParts = _action.Split('?');
                    if (_actionParts.Length > 1) {
                        rPage.Form.Action = ClientHelper.HostUrl + rRequest.ServerVariables["PATH_INFO"] + "?" + _actionParts[1];
                    } else {
                        rPage.Form.Action = ClientHelper.HostUrl + rRequest.ServerVariables["PATH_INFO"];
                    }
                }
                log.Debug("Fix Form action:" + _action);
            } catch (Exception ex) {
                log.Error("Fix Form action exception:" + ex.Message);
            }
        }
        private static String BuildFormAction(HttpRequest rRequest) {
            String url = rRequest.Url.ToString();
            String appPath = rRequest.ApplicationPath;
            log.Debug("ApplicationPath : " + appPath);
            String pathInfo = rRequest.ServerVariables["PATH_INFO"];
            log.Debug("PATH_INFO : " + pathInfo);
            url = url.Substring(url.IndexOf(pathInfo));
            log.Debug("Full PATH_INFO : " + url);

            if (appPath != "/") {
                String pattern = "^(" + appPath + ").*";
                Match mat = Regex.Match(url, pattern, RegexOptions.IgnoreCase);
                if (mat != null && mat.Groups.Count == 2) {
                    String val = mat.Groups[1].Value;
                    url = url.Substring(url.IndexOf(val) + val.Length + 1);
                }
                log.Debug("Filter ApplicationPath: " + url);
            }

            if (url.Length > 1 && url.IndexOf("/") == 0) {
                url = url.Substring(1);
            }

            return url;
        }
    }
}
